<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Models\User;
use Mockery\Exception;

class AuthTokenMiddleware
{
    // 不拦截的路由
    protected  $except = [
        'admin/auth/login',
        'admin/auth/register',
        'admin',  // 测试路由1
        'home',   // 测试路由2
        'test'    // 测试路由3
    ];

    protected  $super = [
        'admin',
    ];
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {

        $isExcept = false;
        $curPath = $request->path();
        if(is_array($this->except)){
            foreach ($this->except as $item){
                if($curPath == $item){
                    $isExcept = true;
                }
            }
        }

         if($isExcept){
//             return response()->json(['error'=>'有权限访问！','code'=>403]);
//             return  redirect('admin/auth/logout') ;
            return $next($request);
        }else{
            //    查询数据库中是否有记录
            $header = $request->header();
            $isAuth = false;

            if(array_key_exists('access-token', $header) && strlen($header['access-token'][0])>20){
                $re_token =str_replace("bearer-",'',$header['access-token'][0]);
                $res = User::where(['token'=>$re_token])->first();



                if($res){
                    // 1.判断当前的用户身份是否已经注销的用户
                    if($res['isDelete'] == 1){
                        return response()->json(['error'=>'当前用户已经注销！请重新注册','code'=>403]);
                    }
                    // 2.考查是否过期
                    $user = auth('api')->setToken($re_token)->user();
                    if(!$user){
                        return response()->json(['error'=>'当前登录已过期！请重新登录','code'=>403]);
                    }


                    $isAuth = true;
                }else{
                    return response()->json(['error'=>'token无效，请重新登录！','code'=>403]);
                }
            }
            if($isAuth){
                return $next($request);
            }else{
                return response()->json(['error'=>'当前没有权限访问！','code'=>403]);
            }
        }
    }
}
